/*
 * SphereTs.cpp
 *
 *  Created on: Sep 1, 2013
 *      Author: marchi
 */

#include "SphereTs.h"
Dvect SphereTs::operator[](size_t n){
	return Tr.at(n).getnormal();
}

void SphereTs::Scale(double Radius){
	for(size_t o=0;o < Tr.size();o++){
		Tr[o].Scale(Radius);
	}
}

SphereTs::SphereTs(int  levels) {
    float t = (1 + sqrt(5.0))/2.0;
    float s = sqrt(1 + t*t);
    // create the 12 vertices
    Dvect v0 = Dvect(t, 1, 0)/s;
    Dvect v1 = Dvect(-t, 1, 0)/s;
    Dvect v2 = Dvect(t, -1, 0)/s;
    Dvect v3 = Dvect(-t, -1, 0)/s;
    Dvect v4 = Dvect(1, 0, t)/s;
    Dvect v5 = Dvect(1, 0, -t)/s;
    Dvect v6 = Dvect(-1, 0, t)/s;
    Dvect v7 = Dvect(-1, 0, -t)/s;
    Dvect v8 = Dvect(0, t, 1)/s;
    Dvect v9 = Dvect(0, -t, 1)/s;
    Dvect v10 = Dvect(0, t, -1)/s;
    Dvect v11 = Dvect(0, -t, -1)/s;

    // create the 20 Tr
    Tr.push_back(Triangle(v0, v8, v4));
    Tr.push_back(Triangle(v1, v10, v7));
    Tr.push_back(Triangle(v2, v9, v11));
    Tr.push_back(Triangle(v7, v3, v1));
    Tr.push_back(Triangle(v0, v5, v10));
    Tr.push_back(Triangle(v3, v9, v6));
    Tr.push_back(Triangle(v3, v11, v9));
    Tr.push_back(Triangle(v8, v6, v4));
    Tr.push_back(Triangle(v2, v4, v9));
    Tr.push_back(Triangle(v3, v7, v11));
    Tr.push_back(Triangle(v4, v2, v0));
    Tr.push_back(Triangle(v9, v4, v6));
    Tr.push_back(Triangle(v2, v11, v5));
    Tr.push_back(Triangle(v0, v10, v8));
    Tr.push_back(Triangle(v5, v0, v2));
    Tr.push_back(Triangle(v10, v5, v7));
    Tr.push_back(Triangle(v1, v6, v8));
    Tr.push_back(Triangle(v1, v8, v10));
    Tr.push_back(Triangle(v6, v1, v3));
    Tr.push_back(Triangle(v11, v7, v5));

    for (int ctr = 0; ctr < levels; ctr++) subdivide();
}
void SphereTs::subdivide(){
    size_t origSize = Tr.size();
    for (size_t i = 0 ; i < origSize ; ++i)
    {
        Triangle& t = Tr[i];
        Dvect a = t.getV0(), b = t.getV1(), c = t.getV2();
        Dvect v1 = Dvect(a[0]+b[0], a[1]+b[1], a[2]+b[2]);
        Dvect v2 = Dvect(a[0]+c[0], a[1]+c[1], a[2]+c[2]);
        Dvect v3 = Dvect(b[0]+c[0], b[1]+c[1], b[2]+c[2]);
        v1.normalize();
        v2.normalize();
        v3.normalize();
        t(v1,v3,v2);
        Tr.push_back(Triangle(a, v1, v2));
        Tr.push_back(Triangle(c, v2, v3));
        Tr.push_back(Triangle(b, v3, v1));
    }

}
SphereTs::~SphereTs() {
	// TODO Auto-generated destructor stub
}

